<template>
  <div>
    <the-user-header :params=this.$store.state.appUser v-if="showTimeOut"/>
      
    <div v-if="isExpired" style="margin-left:16px;margin-top:10px;">
      <router-link to="once-card-pay">
        <span style="color:#ff0000" v-text="expireMsg"></span>
      </router-link>
    </div>
    <group  title="获取优惠">
      <x-input title="我的优惠" 
        :placeholder="(myAgencyCode === '-1')?'输入优惠代码':'已经绑定优惠代码'" 
        v-model="agencyCode" 
        :disabled="(myAgencyCode === '-1' )?false:true">
        <x-button 
        slot="right" 
        type="primary" 
        mini 
        @click.native="bindAgencyCode" 
        :disabled="(myAgencyCode === '-1' )?false:true">提交</x-button>
      </x-input>
    </group> 
    <group  title="月卡消费记录" v-if="allMyCard === 1">
      <selector v-model="selectedCardId" title="选择卡号" :options="myCardVK" @on-change="getCardInfo"></selector>
    </group>
    <group gutter="0" v-show="selectedCardId !== -1">  
      <cell title="卡类型" :value="(card.cardType === 10011002 ? '包月卡' : '次卡')"></cell>
      <cell title="绑卡工种" :value="getWorkById(card.workType)"></cell>
      <cell title="到期时间" :value="card.expireDate"></cell> 
      <cell title="单卡练习次数" :value="card.consumeCount" v-if="(card.cardType === 10011002)"> </cell>
    </group>

    <group  title="消费情况">
      <cell title="消费金额" :value="this.$store.state.appUser.consumeAmount | formatMoney">
        <inline-loading v-if="this.$store.state.appUser.consumeAmount === -1"></inline-loading>
      </cell>
      <cell title="做题次数" :value="this.$store.state.appUser.consumeCount + '次'">
        <inline-loading v-if="this.$store.state.appUser.consumeCount === -1"></inline-loading>
      </cell>
      <cell 
        style="color:#04be02"
        title="做题记录" 
        :value="(historyCount>10)?10:historyCount + '条'" 
        is-link
        link="/review-exercises">
      </cell>
    </group>
    <group>
      <cell title="关于" @click.native="raiseAbout">润皓备考</cell>
    </group>
  </div>  
</template>
<script>
import TheUserHeader from './commons/TheUserHeader'

import {
  Card,
  Group,
  Panel,
  Cell,
  XButton,
  XInput,
  InlineLoading,
  stringTrim,
  Selector
  } from 'vux'
import { mapGetters, mapActions } from 'vuex'
// const TheUserHeader = () => import('./commons/TheUserHeader')
export default {
  components: {
    Card,
    Group,
    Panel,
    Cell,
    XButton,
    XInput,
    InlineLoading,
    TheUserHeader,
    stringTrim,
    Selector
  },
  data () {
    return {
      isExpired: false, // 用户卡过期或者用户卡禁用
      expireMsg: '',  // 过期信息
      userCardInfo: {}, // 用户卡信息
      tmpCount: 0, // 历史记录数
      agencyCode: '',
      agencyList: [],
      agencyPlaceholder: '',
      selectedCardId: -1,
      card: {},
      showTimeOut: false
    }
  },
  mounted () {

  },
  computed: {
    // 映射getters方法，做为计算属性
    ...mapGetters([
      'myCardVK',     // 用户卡的键值对
      'allCardInfo'   // 所有卡的信息
    ]),

    // 计算历史记录个数
    historyCount: function () {
      for (let i = 0; i < localStorage.length; i++) {
        var startIndex = localStorage.key(i).indexOf('E-20')
        if (startIndex === 0) {
          this.tmpCount += 1
        }
      }
      return this.tmpCount
    },
    myAgencyCode: function () {
      var code = this.$store.state.appUser.agencyCode
      if (code === null || code === '') {
        return '-1'
      } else {
        return code
      }
    },
    allMyCard: function () {
      var cardLength = this.$store.state.userAllCardInfo.length
      if (cardLength > 0) {
        return 1
      } else {
        return 0
      }
    }
    // computed end
  },
  methods: {
    // 关于
    raiseAbout: function () {
      this.$vux.alert.show({
        'title': '关于润皓备考',
        'content': '<ul style="text-align:left;"><li>版本号：2.0.0</li><li>版权所有：润皓信息科技</li><li>联系我们：mkd@raiseinfo.cn</li></ul>'
      })
    },
    // 映射action的方法，作为method
    // userCenterInit
    ...mapActions([
      'userCenterInit',
      'getUserInfo'
    ]),

    // 获取卡的具体信息
    getCardInfo: function () {
      console.log(this.selectedCardId)
      if (this.selectedCardId) {
        var allcard = this.allCardInfo
        console.log(allcard)
        var card = []
        for (var i = 0; i < allcard.length; i++) {
          if (allcard[i].cardNo === this.selectedCardId) {
            card = allcard[i]
            console.log('选择的卡为')
            console.log(card)
          }
        }
        this.card = card
      }
    },

    // 根据key获得工种的名字
    getWorkById: function (key) {
      var work = this.$store.state.workTypeKV
      for (var i = 0; i < work.length; i++) {
        if (work[i].key === key) {
          return work[i].value
        }
      }
    },

    // 绑定优惠代码
    bindAgencyCode: function () {
      if (this.agencyCode.length !== 0) {
        var agencyCode = stringTrim(this.agencyCode)
        var agencyList = this.$store.state.agencyList
        console.log(agencyList)
        console.log('Agency Code is ' + agencyCode)
        if (JSON.stringify(agencyList).indexOf(agencyCode) > 0) {
          this.$http.get(this.$store.state.vxPersonalBind + '?openId=' + this.$store.state.openId + '&agencyCode=' + agencyCode).then((res) => {
            console.log(res)
            if (res.data.code === 1) {
              this.$vux.alert.show({title: '提示消息', content: '因为您的微信昵称包含特殊字符，请您更改昵称再次登录系统。'})
            } else if (res.data.code === 0) {
              console.log('Agency bind success')
              this.getUserInfo()
              this.$vux.alert.show({title: '提示消息', content: '您输入的优惠代码绑定成功！'})
            } else {
              this.$vux.alert.show({title: '提示消息', content: res.data.msg})
            }
          }).catch((error) => {
            console.log(error.response)
          })
        } else {
          console.log('Agency bind fail,Agency code not found')
          this.$vux.alert.show({title: '提示消息', content: '您输入的优惠代码没有注册，请核实后再试！'})
        }
      } else {
        console.log('代码无效')
        this.$vux.alert.show({title: '提示消息', content: '您输入有效的优惠代码！'})
      }
    }

    // method end
  },
  created () {
    // this.$nextTick(() => {
    //   this.$vux.loading.show({text: '加载中...'})
    //   this.userCenterInit()
    //   this.$vux.loading.hide()
    // })
    setTimeout(() => {
      this.showTimeOut = true
    }, 100)
    this.userCenterInit()
    console.log('组件Created，用户信息：')
    console.log(this.$store.state.appUser)
    var appUserObj = this.$store.state.appUser
    if (appUserObj.headIcon.length === 0 || stringTrim(appUserObj.nickName).length === 0) {
      this.$http.get(this.$store.state.vxPersonalBind + '?openId=' + appUserObj.openId).then((res) => {
        console.log('用户重新绑定,返回结果:')
        console.log(res.data)
        console.log('更新用户信息')
        this.getUserInfo()
      }).catch((error) => {
        console.log(error.response)
      })
    } else {
      console.log('用户无需重新绑定')
    }
    // end create
  }
}
</script>

<style>
.memberheader{
    height: 90px;
}

</style>
